import React, { useState, useRef, useEffect } from 'react';
import './styles.scss';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';

const Code = ({ inline, className, children, ...props }) => {
    // 检查是否是内联代码（没有语言标识）或者明确指定为内联
    if (inline || !className) {
        return (
            <code
                className={className}
                style={{
                    background: '#F2F3F5',
                    padding: '2px 4px',
                    borderRadius: '4px',
                    fontFamily: "'Fira Code', monospace",
                    fontSize: '0.9em',
                    color: '#1D2129'
                }}
                {...props}
            >
                {children}
            </code>
        );
    }

    // 对于代码块，使用完整的代码块样式
    const match = /language-(\w+)/.exec(className || '');
    const language = match ? match[1] : '';
    const code = String(children).replace(/\n$/, '');

    return (
        <div className="code-wrapper">
            <div className="code-header">
                <div className="code-language">{language || 'plaintext'}</div>
                <button className="copy-button" onClick={() => navigator.clipboard.writeText(code)}>
                    <i className="ri-file-copy-line" />
                    复制代码
                </button>
            </div>
            <div className="code-content">
                <SyntaxHighlighter
                    language={language || 'plaintext'}
                    style={vscDarkPlus}
                    customStyle={{
                        margin: 0,
                        padding: '16px',
                        background: '#1e1e1e',
                        fontSize: '14px',
                        lineHeight: '1.5',
                        fontFamily: "'Fira Code', monospace",
                    }}
                >
                    {code}
                </SyntaxHighlighter>
            </div>
        </div>
    );
}

export default Code;